'''
Author: didiplus 
Date: 2024-07-19 10:06:20
LastEditors: didiplus 
LastEditTime: 2024-07-19 10:16:14
FilePath: \pythonscript\dev_script\backup_huawei_config.py
Description: 
Copyright (c) 2024 by didiplus, All Rights Reserved. 
'''
from paramiko import SSHClient, AutoAddPolicy
import schedule
from time import sleep
from loguru import logger
from datetime import datetime

class Datacom():
    def __init__(self, server, username, password):
        self.server = server
        self.username = username
        self.password = password
        
        self.client = self._get_client()
        self.cli = self.client.invoke_shell()
        self.cli.send('screen-length 0 temporary\n')
        sleep(5)
        self.cli.recv(999999)
        
    def _get_client(self):
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy)
        client.connect(self.server, username=self.username, password=self.password,look_for_keys=False)
        return client
        
    def command(self, cmd):
        self.cli.send("{}\n".format(cmd))
        sleep(5)
        return self.cli.recv(999999).decode()
            
    def download_config(self, target, config_path='/vrpcfg.cfg'):
        logger.info("copy config file with sftp-------------------") # 打印提示信息
        another_client = self._get_client()  # 创建另一个SSH连接客户端
        sftp = another_client.open_sftp()  # 打开SFTP会话
        sftp.get(config_path, target)  # 下载配置文件到本地路径
        another_client.close()  # 关闭SSH连接

    def close(self):
        self.client.close()


def backup_conf(device_ip,username,password,device_name):
    datacom = Datacom(device_ip,username,password)  #实例化Datacom
    last_downloadtime = datetime.now()
    datacom.download_config('{}_{}_{}_{}.zip'.format(
        last_downloadtime.year,
        last_downloadtime.month,
        last_downloadtime.day,
        device_name
    ))  #调用download_config方法实现备份
    logger.info("backup config success")
    datacom.close()

if __name__ == "__main__":
    device_ip = "192.168.56.10" #
    username = "dev_user"
    password = "Huawei@123"
    device_name = "X_T1_AGG1"
    # backup_conf(device_ip,username,password,device_name)
    schedule.every(1).minutes.do(backup_conf,device_ip,username,password,device_name)
    while True:
        schedule.run_pending()